const mongoose = require("mongoose");
const usersModel = mongoose.model("users");
const { md5, secretKey } = require("../util/salt");
const jwt = require("jsonwebtoken");
const axios = require('axios')
let search = async (find, { page = 1, limit = 10 } = {}) => await usersModel.find(find).skip((page - 1) * limit).limit(limit).sort({ _id: -1 }).exec();
// 注册
let reg = async ({ nickName, userName, userPassword, date = new Date(), status = true, img = [] }) => {
    let data = await usersModel.findOne({ userName });
    data = !data ? await usersModel.create({ nickName, userName, userPassword, date: [date], status, img }) : false;
    return data;
}
module.exports = {
    reg,
    search,
    // 登陆
    login: async ({ code, nickName, img, appid = 'wxc082bf18720fe908', secret = '011f3878bc6b26937fb1caf09a6f7981' }) => {
        const { data: key } = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
            params: {
                appid,
                js_code: code,
                grant_type: "authorization_code",
                secret,
            }
        })
        const result = await reg({ nickName, img, userName: key.openid, userPassword: key.session_key });
        //如果有账号直接返回token
        if (!result) {
            const { openid } = key;
            let data = {};
            const user = await usersModel.findOne({ userName: openid });
            const payload = {
                openid: user.userName,
            };
            data.nickName = user.nickName;
            data.img = user.img;
            data._id = user._id;
            data.delivery = user.delivery;
            data.token = jwt.sign(payload, secretKey, {
                expiresIn: 60 * 60 * 24, // 秒
            });
            return data

        } else {//如果没注册过就用注册后的账号返回token
            let data = {};
            const user = await usersModel.findOne({ userName: result.userName });
            const payload = {
                openid: user.userName,

            };
            data.nickName = user.nickName;
            data.img = user.img;
            data._id = user._id;
            data.delivery = user.delivery;
            data.token = jwt.sign(payload, secretKey, {
                expiresIn: 60 * 60 * 24, // 秒
            });
            return data

        }
    },

    // 获取数据-分页
    get: async ({ page, limit }) => {
        limit = ~~limit;
        const result = {};
        result.total = await usersModel.countDocuments();
        result.rows = await usersModel.find().skip((page - 1) * limit).limit(limit).sort({ _id: -1 }).exec();
        return result;
    },
    // 添加时间
    addDate: async ({ _id, date }) => await usersModel.updateOne({ _id }, { $push: { loginDate: date } }),
    // 更新
    update: async (conditions, doc) => await usersModel.updateOne(conditions, doc),
    //根据find条件查询

    // 删除
    del: async ({ _id }) => await usersModel.deleteOne({ _id }),
    //添加图片
    addImg: async ({ _id, url }) => await usersModel.updateOne({ _id }, { $push: { img: url } }),

    //删除用户图片
    removeImg: async ({ _id, url }) =>
        // let user = await search({ _id });//先获取用户对象
        // console.log(user);
        // user.img.pull(url);//删除用户对象 的 属性imgs数组 里面的值
        // return await user.save();//保存数据
        await usersModel.updateOne({ _id }, { $pull: { img: url } }),
    //添加收货地址
    addAddress: async ({ _id, name, phone, address }) => await usersModel.updateOne({ _id }, { $push: {delivery:{ name, phone, address }} })

}